<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}
session_start();
require_once '../config.php';

// 检查是否登录
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}


// 获取系统设置
$settings = getSettings();
$error = '';
$success = '';
$logs = [];
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;
$region_filter = $_GET['region_filter'] ?? '';

// 处理批量删除
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'batch_delete') {
    if (isset($_POST['selected_ids']) && !empty($_POST['selected_ids'])) {
        $ids = $_POST['selected_ids'];
        try {
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $stmt = $pdo->prepare("DELETE FROM qq_access_logs WHERE id IN ($placeholders)");
            $stmt->execute($ids);
            $deleted_count = $stmt->rowCount();
            $success = "成功删除 {$deleted_count} 条记录";
        } catch (PDOException $e) {
            $error = '删除失败：' . $e->getMessage();
        }
    } else {
        $error = '请选择要删除的记录';
    }
}

// 构建查询条件
$where = [];
$params = [];

if (!empty($search)) {
    $where[] = "qq LIKE ?";
    $params[] = "%{$search}%";
}
if (!empty($region_filter)) {
    $where[] = "region LIKE ?";
    $params[] = "%{$region_filter}%";
}

$whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// 获取总记录数
$stmt = $pdo->prepare("SELECT COUNT(*) FROM qq_access_logs $whereClause");
$stmt->execute($params);
$total = $stmt->fetchColumn();
$total_pages = ceil($total / $per_page);

// 获取分页数据
$stmt = $pdo->prepare("
    SELECT * FROM qq_access_logs 
    $whereClause 
    ORDER BY created_at DESC 
    LIMIT $offset, $per_page
");
$stmt->execute($params);
$logs = $stmt->fetchAll();

// 处理查询请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'query') {
    $qq = trim($_POST['qq'] ?? '');
    
    if (empty($qq)) {
        $error = '请输入QQ号';
    } else {
        try {
            // 查询QQ绑定记录
            $stmt = $pdo->prepare("SELECT * FROM qq_access_logs WHERE qq_number = ? ORDER BY created_at DESC");
            $stmt->execute([$qq]);
            $logs = $stmt->fetchAll();
            
            if (empty($logs)) {
                $error = '未找到该QQ号的绑定记录';
            }
        } catch (PDOException $e) {
            $error = '查询失败：' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title']); ?> - 查询记录</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
        /* 移动端表格优化 */
        @media (max-width: 767.98px) {
            .table-responsive {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }
            
            .table-nowrap th, 
            .table-nowrap td {
                white-space: nowrap;
            }
            
            /* 表格内容紧凑显示 */
            .table-sm th, 
            .table-sm td {
                padding: 0.3rem;
                font-size: 0.875rem;
            }
            
            /* 确保水平滚动条可见 */
            .table-responsive-sm {
                position: relative;
            }
            
            /* 移动端分页紧凑显示 */
            .pagination .page-item {
                margin: 0 1px;
            }
            
            .pagination .page-link {
                padding: 0.4rem 0.6rem;
                min-width: 32px;
                text-align: center;
                font-size: 0.875rem;
            }
            
            /* 移动端分页样式优化 */
            .pagination-mobile .page-link {
                padding: 0.25rem 0.5rem;
                font-size: 0.875rem;
            }
        }
        @media (max-width: 767.98px) {
            .table-qb-mobile {
                display: block;
                width: 100%;
            }
            .table-qb-mobile thead { display: none; }
            .table-qb-mobile tbody { display: block; }
            .table-qb-mobile tr { display: block; margin-bottom: 1rem; border: 1px solid #eee; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); background: #fff; }
            .table-qb-mobile td { display: flex; width: 100%; border: none; border-bottom: 1px solid #f2f2f2; align-items: center; padding: 0.5rem 1rem; font-size: 15px; }
            .table-qb-mobile td:last-child { border-bottom: none; }
            .table-qb-mobile .qb-label { min-width: 80px; color: #888; font-size: 13px; margin-right: 8px; display: inline-block; }
            .table-qb-mobile .qb-actions { justify-content: flex-end; }
        }
        @media (min-width: 768px) {
            .table-qb-mobile .qb-label { display: none !important; }
        }
    </style>
</head>

<body>
<!--页面loading-->
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader">
        <div class="round_spinner">
            <div class="spinner"></div>
            <img src="../assets/images/loading-logo.png" alt="">
        </div>
    </div>
</div>
<!--页面loading end-->

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <?php $current_page = 'qb_query'; include 'navbar.php'; ?>
        
        <!--页面主要内容-->
        <main class="lyear-layout-content">
            <div class="container-fluid p-t-15">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-header">
                                <h4>查询记录</h4>
                            </div>
                            <div class="card-toolbar">
                                <form class="search-bar" method="get">
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <select class="form-control" name="region_filter">
                                                <option value="">全部地区</option>
                                                <option value="北京" <?php if($region_filter=="北京") echo 'selected'; ?>>北京</option>
                                                <option value="天津" <?php if($region_filter=="天津") echo 'selected'; ?>>天津</option>
                                                <option value="上海" <?php if($region_filter=="上海") echo 'selected'; ?>>上海</option>
                                                <option value="重庆" <?php if($region_filter=="重庆") echo 'selected'; ?>>重庆</option>
                                                <option value="河北" <?php if($region_filter=="河北") echo 'selected'; ?>>河北</option>
                                                <option value="山西" <?php if($region_filter=="山西") echo 'selected'; ?>>山西</option>
                                                <option value="辽宁" <?php if($region_filter=="辽宁") echo 'selected'; ?>>辽宁</option>
                                                <option value="吉林" <?php if($region_filter=="吉林") echo 'selected'; ?>>吉林</option>
                                                <option value="黑龙江" <?php if($region_filter=="黑龙江") echo 'selected'; ?>>黑龙江</option>
                                                <option value="江苏" <?php if($region_filter=="江苏") echo 'selected'; ?>>江苏</option>
                                                <option value="浙江" <?php if($region_filter=="浙江") echo 'selected'; ?>>浙江</option>
                                                <option value="安徽" <?php if($region_filter=="安徽") echo 'selected'; ?>>安徽</option>
                                                <option value="福建" <?php if($region_filter=="福建") echo 'selected'; ?>>福建</option>
                                                <option value="江西" <?php if($region_filter=="江西") echo 'selected'; ?>>江西</option>
                                                <option value="山东" <?php if($region_filter=="山东") echo 'selected'; ?>>山东</option>
                                                <option value="河南" <?php if($region_filter=="河南") echo 'selected'; ?>>河南</option>
                                                <option value="湖北" <?php if($region_filter=="湖北") echo 'selected'; ?>>湖北</option>
                                                <option value="湖南" <?php if($region_filter=="湖南") echo 'selected'; ?>>湖南</option>
                                                <option value="广东" <?php if($region_filter=="广东") echo 'selected'; ?>>广东</option>
                                                <option value="海南" <?php if($region_filter=="海南") echo 'selected'; ?>>海南</option>
                                                <option value="四川" <?php if($region_filter=="四川") echo 'selected'; ?>>四川</option>
                                                <option value="贵州" <?php if($region_filter=="贵州") echo 'selected'; ?>>贵州</option>
                                                <option value="云南" <?php if($region_filter=="云南") echo 'selected'; ?>>云南</option>
                                                <option value="陕西" <?php if($region_filter=="陕西") echo 'selected'; ?>>陕西</option>
                                                <option value="甘肃" <?php if($region_filter=="甘肃") echo 'selected'; ?>>甘肃</option>
                                                <option value="青海" <?php if($region_filter=="青海") echo 'selected'; ?>>青海</option>
                                                <option value="台湾" <?php if($region_filter=="台湾") echo 'selected'; ?>>台湾</option>
                                                <option value="内蒙古" <?php if($region_filter=="内蒙古") echo 'selected'; ?>>内蒙古</option>
                                                <option value="广西" <?php if($region_filter=="广西") echo 'selected'; ?>>广西</option>
                                                <option value="西藏" <?php if($region_filter=="西藏") echo 'selected'; ?>>西藏</option>
                                                <option value="宁夏" <?php if($region_filter=="宁夏") echo 'selected'; ?>>宁夏</option>
                                                <option value="新疆" <?php if($region_filter=="新疆") echo 'selected'; ?>>新疆</option>
                                                <option value="香港" <?php if($region_filter=="香港") echo 'selected'; ?>>香港</option>
                                                <option value="澳门" <?php if($region_filter=="澳门") echo 'selected'; ?>>澳门</option>
                                            </select>
                                        </div>
                                        <input type="text" class="form-control" name="search" placeholder="请输入QQ号" value="<?php echo htmlspecialchars($search); ?>">
                                        <div class="input-group-append">
                                            <button class="btn btn-primary" type="submit">搜索</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                            <div class="card-body">
                                <?php if ($error): ?>
                                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                        <strong>错误！</strong> <?php echo $error; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($success): ?>
                                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                                        <strong>成功！</strong> <?php echo $success; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                <?php endif; ?>
                                
                                <!-- 批量操作按钮 -->
                                <div class="mb-3">
                                    <button id="batch-delete-btn" class="btn btn-danger" disabled>
                                        <i class="mdi mdi-delete-forever"></i> 批量删除
                                    </button>
                                    <span id="selected-count" class="ms-2 text-muted">已选择 0 项</span>
                                </div>
                                
                                <form id="batch-form" method="post">
                                    <input type="hidden" name="action" value="batch_delete">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-nowrap table-qb-mobile">
                                            <thead>
                                                <tr>
                                                    <th>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="select-all">
                                                            <label class="form-check-label" for="select-all"></label>
                                                        </div>
                                                    </th>
                                                    <th>QQ</th>
                                                    <th>手机号</th>
                                                    <th>归属地</th>
                                                    <th>经度</th>
                                                    <th>纬度</th>
                                                    <th>地区</th>
                                                    <th>IP地址</th>
                                                    <th>查询时间</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (!empty($logs)): ?>
                                                    <?php foreach ($logs as $log): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="form-check">
                                                                <input class="form-check-input record-checkbox" type="checkbox" name="selected_ids[]" value="<?php echo $log['id']; ?>">
                                                                <label class="form-check-label"></label>
                                                            </div>
                                                        </td>
                                                        <td><span class="qb-label">QQ</span><?php echo htmlspecialchars($log['qq']); ?></td>
                                                        <td><span class="qb-label">手机号</span><?php echo empty($log['phone']) ? '没有找到' : htmlspecialchars($log['phone']); ?></td>
                                                        <td><span class="qb-label">归属地</span><?php echo empty($log['phonediqu']) ? '没有找到' : htmlspecialchars($log['phonediqu']); ?></td>
                                                        <td><span class="qb-label">经度</span><?php echo htmlspecialchars($log['longitude'] ?? ''); ?></td>
                                                        <td><span class="qb-label">纬度</span><?php echo htmlspecialchars($log['latitude'] ?? ''); ?></td>
                                                        <td><span class="qb-label">地区</span><?php echo htmlspecialchars($log['region'] ?? ''); ?></td>
                                                        <td><span class="qb-label">IP地址</span><?php echo htmlspecialchars($log['ip'] ?? ''); ?></td>
                                                        <td><span class="qb-label">查询时间</span><?php echo htmlspecialchars($log['created_at']); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="9" class="text-center">暂无记录</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </form>
                                
                                <!-- 分页 -->
                                <?php if ($total_pages > 1): ?>
                                    <!-- 桌面端分页 -->
                                    <div class="d-none d-md-block">
                                        <ul class="pagination justify-content-center mt-3">
                                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&region_filter=<?php echo urlencode($region_filter); ?>" tabindex="-1" aria-disabled="true">上一页</a>
                                            </li>
                                            
                                            <?php
                                            $start_page = max(1, $page - 2);
                                            $end_page = min($total_pages, $page + 2);
                                            
                                            if ($start_page > 1) {
                                                echo '<li class="page-item"><a class="page-link" href="?page=1&search='.urlencode($search).'&region_filter='.urlencode($region_filter).'">1</a></li>';
                                                if ($start_page > 2) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                            }
                                            
                                            for ($i = $start_page; $i <= $end_page; $i++) {
                                                echo '<li class="page-item '.($i == $page ? 'active' : '').'"><a class="page-link" href="?page='.$i.'&search='.urlencode($search).'&region_filter='.urlencode($region_filter).'">'.$i.'</a></li>';
                                            }
                                            
                                            if ($end_page < $total_pages) {
                                                if ($end_page < $total_pages - 1) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                                echo '<li class="page-item"><a class="page-link" href="?page='.$total_pages.'&search='.urlencode($search).'&region_filter='.urlencode($region_filter).'">'.$total_pages.'</a></li>';
                                            }
                                            ?>
                                            
                                            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&region_filter=<?php echo urlencode($region_filter); ?>">下一页</a>
                                            </li>
                                        </ul>
                                    </div>
                                    
                                    <!-- 移动端分页 - 与桌面端相同的页码显示 -->
                                    <div class="d-block d-md-none">
                                        <ul class="pagination pagination-mobile justify-content-center mt-3">
                                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&region_filter=<?php echo urlencode($region_filter); ?>">
                                                    <i class="mdi mdi-chevron-left"></i>
                                                </a>
                                            </li>
                                            
                                            <?php
                                            // 移动端显示更少的页码，但保持与桌面端相同的逻辑
                                            $mobile_start = max(1, $page - 1);
                                            $mobile_end = min($total_pages, $page + 1);
                                            
                                            // 第一页
                                            if ($mobile_start > 1) {
                                                echo '<li class="page-item"><a class="page-link" href="?page=1&search='.urlencode($search).'&region_filter='.urlencode($region_filter).'">1</a></li>';
                                                if ($mobile_start > 2) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                            }
                                            
                                            // 当前页附近的页码
                                            for ($i = $mobile_start; $i <= $mobile_end; $i++) {
                                                echo '<li class="page-item '.($i == $page ? 'active' : '').'"><a class="page-link" href="?page='.$i.'&search='.urlencode($search).'&region_filter='.urlencode($region_filter).'">'.$i.'</a></li>';
                                            }
                                            
                                            // 最后一页
                                            if ($mobile_end < $total_pages) {
                                                if ($mobile_end < $total_pages - 1) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                                echo '<li class="page-item"><a class="page-link" href="?page='.$total_pages.'&search='.urlencode($search).'&region_filter='.urlencode($region_filter).'">'.$total_pages.'</a></li>';
                                            }
                                            ?>
                                            
                                            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&region_filter=<?php echo urlencode($region_filter); ?>">
                                                    <i class="mdi mdi-chevron-right"></i>
                                                </a>
                                            </li>
                                        </ul>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <!--End 页面主要内容-->
    </div>
</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="../assets/js/jquery.mCustomScrollbar.concat.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="../assets/js/main.min.js"></script>
<script>
$(document).ready(function() {
    // 检测是否为移动设备
    var isMobile = window.matchMedia("only screen and (max-width: 767.98px)").matches;
    
    // 移动端表格优化
    if (isMobile) {
        // 为表格添加小尺寸类
        $('.table').addClass('table-sm');
        
        // 添加表格滚动提示
        $('.table-responsive').each(function() {
            if ($(this).find('table').width() > $(this).width()) {
                var $scrollHint = $('<div class="text-muted text-center mt-2 mb-2"><small><i class="mdi mdi-gesture-swipe"></i> 左右滑动查看更多</small></div>');
                $(this).before($scrollHint);
                
                // 3秒后淡出提示
                setTimeout(function() {
                    $scrollHint.fadeOut(1000);
                }, 3000);
            }
        });
    }
    
    // 批量选择功能
    var $selectAll = $('#select-all');
    var $recordCheckboxes = $('.record-checkbox');
    var $batchDeleteBtn = $('#batch-delete-btn');
    var $selectedCount = $('#selected-count');
    var $batchForm = $('#batch-form');
    
    // 全选/取消全选
    $selectAll.on('change', function() {
        var isChecked = $(this).prop('checked');
        $recordCheckboxes.prop('checked', isChecked);
        updateSelectedCount();
    });
    
    // 单个选择
    $recordCheckboxes.on('change', function() {
        updateSelectedCount();
        // 如果所有复选框都被选中，则全选框也被选中
        $selectAll.prop('checked', $recordCheckboxes.length === $recordCheckboxes.filter(':checked').length);
    });
    
    // 更新已选择的数量
    function updateSelectedCount() {
        var count = $recordCheckboxes.filter(':checked').length;
        $selectedCount.text('已选择 ' + count + ' 项');
        $batchDeleteBtn.prop('disabled', count === 0);
    }
    
    // 批量删除按钮点击事件
    $batchDeleteBtn.on('click', function() {
        if (confirm('确定要删除选中的 ' + $recordCheckboxes.filter(':checked').length + ' 条记录吗？此操作不可恢复！')) {
            $batchForm.submit();
        }
    });
});
</script>
</body>
</html> 